package com.sit.estatemanagementserver.service;

import com.sit.estatemanagementserver.dao.ImageDao;
import com.sit.estatemanagementserver.enity.Image;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class ImageService {

    @Value("${image.path}")
    private String uploadDir;

    private Path rootLocation;

    @Autowired
    ImageDao imageDao;

    @PostConstruct
    public void init() {
        try {
            this.rootLocation = Paths.get(uploadDir);
            Files.createDirectories(rootLocation);
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize storage location", e);
        }
    }

    public Image processImageUpload(MultipartFile file, String filename) {
        // 无需修改，此处的逻辑与重构后的DAO层兼容
        storeFileToDisk(file, filename);
        String relativePath = "/image/" + filename;
        Image image = new Image(filename, relativePath);

        Image existingImage = imageDao.getImageById(filename);
        if (existingImage == null) {
            imageDao.addImage(image);
        } else {
            imageDao.updateImage(image);
        }
        return image;
    }

    private String createFilenameFromWorkOrder(MultipartFile file, String workOrderId) {
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String fileExtension = "";
        int lastDotIndex = originalFilename.lastIndexOf('.');
        if (lastDotIndex >= 0) {
            fileExtension = originalFilename.substring(lastDotIndex);
        }
        return workOrderId + "-Complaint" + fileExtension;
    }

    private void storeFileToDisk(MultipartFile file, String newFilename) {
        try {
            if (file.isEmpty()) throw new RuntimeException("上传失败：文件为空。");
            Path destinationFile = this.rootLocation.resolve(newFilename).normalize().toAbsolutePath();
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, destinationFile, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException e) {
            throw new RuntimeException("存储文件失败: " + newFilename, e);
        }
    }
}